
const fs: any = null;

/**
 * 代码生成脚本
 * */
export class CodeWriter {
    private blockStart: string = "{";
    private blockEnd: string = "}";
    private blockFromNewLine: boolean = false;
    private indentStr: string = "\t";
    private endOfLine: string = "";
    private lines: string = "";
    private fileMark: string = "";
    private indent: number = 0;
    private str: string = "";


    constructor(config?: ICodeWriterConfig) {
        if (!config) return;

        this.blockFromNewLine = !!config.blockFromNewLine;
        config.blockStart && (this.blockStart = config.blockStart);
        config.blockEnd && (this.blockEnd = config.blockEnd);
        config.fileMark && (this.fileMark = config.fileMark);
        config.endOfLine && (this.endOfLine = config.endOfLine);
    }

    writeMark(): void {

    }

    writeln(fmt?: string, ...args: any[]): CodeWriter {
        if (!fmt) {
            this.str += "\n";
        } else {
            let newLine = this.blockFromNewLine ? "\n" : "";
            let startLine = this.str.length > 0 ? "\n" : "";
            this.str = this.str + startLine + this.currIndentStr + this.strFrame(fmt, ...args) + newLine;
        }
        return this;
    }

    writeContinue(fmt?: string, ...args: any[]) {
        this.str += this.strFrame(fmt!, ...args);
        return this;
    }

    startBlock(): CodeWriter {
        let newLine = this.blockFromNewLine ? this.currIndentStr : "";
        this.str = this.str + newLine + this.blockStart;
        this.incIndent();
        return this;
    }

    endBlock(): CodeWriter {
        this.decIndent();
        this.str = this.str + "\n" + this.currIndentStr + this.blockEnd;
        return this;
    }

    incIndent(): CodeWriter {
        ++this.indent;
        return this;
    }

    decIndent(): CodeWriter {
        --this.indent;
        return this;
    }

    reset(): void {
        this.indent = 0;
        this.str = "";
    }

    toString(): string {
        return this.str;
    }

    save(filePath: string): void {
        fs.writeFileSync(filePath, this.str)
    }

    private strFrame(str: string, ...ages: any[]) {
        for (let i = 0; i < ages.length; i++) {
            str = str.replace(`{${i}}`, ages[i]);
        }
        return str;
    }

    private get currIndentStr() {
        if (this.indent < 1) return "";
        let str = "";
        for (let i = 0; i < this.indent; i++) {
            str += this.indentStr;
        }
        return str;
    }
}

interface ICodeWriterConfig {
    blockStart?: string;
    blockEnd?: string;
    blockFromNewLine?: boolean;
    usingTabs?: boolean;
    endOfLine?: string;
    fileMark?: string;
}